﻿using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.TestCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Test
{
    public partial class PurchaseMaterialSelectForm : Form
    {

        private ApiClient _apiClient;
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private readonly Action<PurchaseMaterialDtos> _onSelected;

        public PurchaseMaterialSelectForm(Action<PurchaseMaterialDtos> onSelected = null)
        {
            InitializeComponent();
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
            _onSelected = onSelected;

            // 配置表格
            ConfigureDataGridView();

            LoadUnit();
            LoadType();
            Loadproperties();
            Search();

        }

        /// <summary>
        /// 配置数据表格
        /// </summary>
        private void ConfigureDataGridView()
        {
            if (dgvpurmater != null)
            {
                dgvpurmater.AllowUserToAddRows = false;
                dgvpurmater.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvpurmater.MultiSelect = false;

                // 绑定双击事件
                dgvpurmater.CellDoubleClick += Dgvpurmater_CellDoubleClick;

                // 绑定单元格点击事件
                dgvpurmater.CellContentClick += Dgvpurmater_CellContentClick;

                // 绑定数据绑定完成事件
                dgvpurmater.DataBindingComplete += Dgvpurmater_DataBindingComplete;
            }
        }

        /// <summary>
        /// 表格双击事件
        /// </summary>
        private void Dgvpurmater_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex < dgvpurmater.Rows.Count)
            {
                SelectMaterial(e.RowIndex);
            }
        }

        /// <summary>
        /// 表格单元格点击事件
        /// </summary>
        private void Dgvpurmater_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var grid = sender as DataGridView;
            if (grid == null) return;

            var columnName = grid.Columns[e.ColumnIndex].Name;

            if (columnName == "colSelect")
            {
                // 选择功能
                SelectMaterial(e.RowIndex);
            }
        }

        /// <summary>
        /// 数据绑定完成事件
        /// </summary>
        private void Dgvpurmater_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            // 确保有选择列
            EnsureSelectionColumn();
        }

        /// <summary>
        /// 确保选择列存在
        /// </summary>
        private void EnsureSelectionColumn()
        {
            if (!dgvpurmater.Columns.Contains("colSelect"))
            {
                var selectCol = new DataGridViewButtonColumn
                {
                    Name = "colSelect",
                    HeaderText = "选择",
                    Text = "选择",
                    UseColumnTextForButtonValue = true,
                    Width = 60
                };
                dgvpurmater.Columns.Add(selectCol);

                // 将选择列放到最后
                selectCol.DisplayIndex = dgvpurmater.Columns.Count - 1;
            }
        }

        /// <summary>
        /// 选择物料
        /// </summary>
        private void SelectMaterial(int rowIndex)
        {
            if (rowIndex < 0 || rowIndex >= dgvpurmater.Rows.Count) return;

            var row = dgvpurmater.Rows[rowIndex];
            if (row.DataBoundItem is PurchaseMaterialDtos material)
            {
                // 调用回调函数，传递选中的物料
                _onSelected?.Invoke(material);

                // 关闭窗体
                this.Close();
            }
        }

        /// <summary>
        /// 获取采购单中的物料信息
        /// </summary>
        private async void Search(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
            {
                    { "pageindex", PageIndex.ToString() },
                    { "pagesize", PageSize.ToString() },
                    { "materialNameOrNumber",this.textmaterialNameOrNumber.Text}

            };
            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<TestApiResult<List<PurchaseMaterialDtos>>>(
                    endpoint: "api/Read/GetPurchaseMaterial",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 将数据绑定到 DataGridView
                dgvpurmater.DataSource = response.pageDatas;
            }
        }

        // 加载单位下拉框数据
        private async Task LoadUnit()
        {
            // 示例：加载下拉框
            var unitResponse = await _apiClient.GetAsync<TestApiResult<List<UnitModelDtos>>>(
                endpoint: "api/Read/GetUnitModel");

            if (unitResponse != null && unitResponse.code == 200)
            {
                // 清空并添加默认项
                cbounit_Id.Items.Clear();
                cbounit_Id.DisplayMember = "unitName"; // 显示名称
                cbounit_Id.ValueMember = "id";                 // 实际值存 ID
                cbounit_Id.DataSource = unitResponse.data;
                cbounit_Id.SelectedItem = null;
            }
        }

        // 加载物料类型下拉框数据
        private async Task LoadType()
        {
            // 示例：加载下拉框
            var materResponse = await _apiClient.GetAsync<TestApiResult<List<Material_TypeDtos>>>(
                endpoint: "api/Read/GetMaterial_TypeDtos");

            if (materResponse != null && materResponse.code == 200)
            {
                // 清空并添加默认项
                cbotype_Id.Items.Clear();
                cbotype_Id.DisplayMember = "typeName"; // 显示名称
                cbotype_Id.ValueMember = "id";                 // 实际值存 ID
                cbotype_Id.DataSource = materResponse.data;
                cbotype_Id.SelectedItem = null;
            }
        }

        // 加载物料属性下拉框数据
        private async Task Loadproperties()
        {
            // 示例：加载下拉框
            var propertiesResponse = await _apiClient.GetAsync<TestApiResult<List<Material_PropertiesDtos>>>(
                endpoint: "api/Read/GetMaterial_PropertiesDtos");

            if (propertiesResponse != null && propertiesResponse.code == 200)
            {
                // 清空并添加默认项
                cboproperties_Id.Items.Clear();
                cboproperties_Id.DisplayMember = "propertiesName"; // 显示名称
                cboproperties_Id.ValueMember = "id";                 // 实际值存 ID
                cboproperties_Id.DataSource = propertiesResponse.data;
                cboproperties_Id.SelectedItem = null;
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();
            if (cbounit_Id.SelectedValue != null)
            {
                queryParams["unit_Id"] = ((int)cbounit_Id.SelectedValue).ToString();
            }

            if (cbotype_Id.SelectedValue != null)
            {
                queryParams["type_Id"] = ((int)cbotype_Id.SelectedValue).ToString();
            }
            if (cboproperties_Id.SelectedValue != null)
            {
                queryParams["properties_Id"] = ((int)cboproperties_Id.SelectedValue).ToString();
            }
            Search(queryParams);
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            textmaterialNameOrNumber.Text=string.Empty;
            cbounit_Id.Text = string.Empty;
            cbotype_Id.Text = string.Empty;
            cboproperties_Id.Text = string.Empty;
            Search();
        }
    }
}
